package NG::Gen::Battle::Battle;
use strict;
use warnings;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(calc_battle);

use NG::Gen::Battle::Calc;

sub calc_battle {
	my ($s1,$s2,$log) = @_;

	prepare_side($s1,$s2);

	my $result;
	push @$log,["start",$s1->{title},$s1->{wc},$s1->{tc},$s2->{title},$s2->{wc},$s2->{tc}];
	my $turn = 0;
	my $dir = 1;
	for(;;){

		$s1->reset_side;
		$s2->reset_side;

		$turn++;
		push @$log,["round",$turn,$s1->{wc},$s1->{tc},$s2->{wc},$s2->{tc}];

		if($result = round($dir,$dir==1?($s1,$s2):($s2,$s1),$log)){
			last;
		}
		if($dir == 1){
			$dir = 2;
		}else{
			$dir = 1;
		}

		unless($turn < 1000){
			$result = 3;
			push @$log,["limit"];
			last;
		}
	}
	push @$log,["end",$result,$s1->{title},$s1->{wc},$s1->{tc},$s2->{title},$s2->{wc},$s2->{tc},$s1->{damage},$s2->{damage},
			];
	if($s1->{tc} < 0 || $s2->{tc} < 0){
		$result = 0;
	}
	return $result;
}
sub prepare_side {
	my ($s1,$s2) = @_;
	$s1->prepare({});
	$s2->prepare({});
}
sub round {
	my ($dir,$s1,$s2,$log) = @_;
	my $result;

	until($result = check_end($dir,$s1,$s2)){

		my $u1 = make_hit($dir,$s1,$s2,$log);
		my $u2 = make_hit(3 - $dir,$s2,$s1,$log);
		
		last unless $result = $u1 || $u2;
	}
	return $result;
}
sub make_hit {
	my ($dir,$s1,$s2,$log) = @_;
	my $u = $s1->get_next;
	unless($u){
		return 0;
	}
	my $ep = $s2->choose_target;
	my $e = $s2->{all}[$ep];

	$s1->check_before_4a($dir,$u,$log);
	$s2->check_before_4t(3-$dir,$e,$log);

	my $ic = $e->{count};
	my $ir = $e->{rest};
	my ($shoot,$damag,$count) = make_shoot($u,$e);
	$s1->{damage} += $damag;
	my $nc = $e->{count};
	my $nr = $e->{rest};

	#push @$log,["result", $dir,$shoot,$count,$damag,$e->{title},$ic,$nc,$ir,$nr];
	my $again = $u->{again};
	$u->{again} = 0;
	push @$log,["hit",$dir,$u->{title},$u->{current},$e->{title},$shoot,$count,$damag,$e->{count},$e->{rest},$again,($e->{count} || $e->{rest}?():("last"))];
	#push @$log,["hit", $dir,$u->{title},$e->{title},$shoot,"$ic - $count = $nc","$ir - $damag = $nr",($e->{count} || $e->{rest}?():("last"))];
	

	if($damag){
		$s1->check_after_4a($dir,$u,$log);
		unless($count){
			$s2->check_after_4t(3-$dir,$e,$log);
		}
	}

	$s2->{tc} -= $count;
	if($e->{damage}){
		$s2->{wc} -= $count;
	}
	return $u;
}
# 0 - next
# 1 - first win
# 2 - second win
# 3 - draw
sub check_end {
	my ($dir,$s1,$s2) = @_;
	if($s1->{wc} and $s2->{wc}){
		return 0;
	}
	elsif($s1->{wc} and !$s2->{wc}){
		return $dir;
	}
	elsif(!$s1->{wc} and $s2->{wc}){
		return 3 - $dir;
	}
	elsif($s1->{tc} and !$s2->{tc}){
		return $dir;
	}
	elsif(!$s1->{tc} and $s2->{tc}){
		return 3 - $dir;
	}
	else{
		return 3;
	}
}



1;
